package com.gusto.samples.cluster;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.gusto.engine.clusterant.algorithms.antsclustering.AntsClusteringAlgorithm;
import com.gusto.engine.clusterant.algorithms.antsclustering.AntsClusteringAlgorithmListener;
import com.gusto.engine.clusterant.algorithms.antsclustering.Plan;
import com.gusto.engine.clusterant.algorithms.antsclustering.ants.Ant;
import com.gusto.engine.clusterant.algorithms.kmeansclustering.Cluster;
import com.gusto.engine.clusterant.algorithms.kmeansclustering.KMeansClustering;

/*

 service:jmx:rmi://localhost/jndi/rmi://localhost:1099/myconnector

 // 1 2 3 => A
 // 6 7 8 => B
 // 5 9 12 => C
 // 4 11 => D 
 // 10 => E

*/

public class ClusterantSample implements AntsClusteringAlgorithmListener {
	
	private Logger log = Logger.getLogger(getClass());
	
	private static AntsClusteringAlgorithm antsClustering;
	private static KMeansClustering kmeansClustering;
	
	public ClusterantSample() {
		super();
		//ApplicationContext factory = new ClassPathXmlApplicationContext("config-clusterant-*.xml");
		ApplicationContext factory = new ClassPathXmlApplicationContext("config/cluster/config-clusterant-core.xml");
		antsClustering = (AntsClusteringAlgorithm)factory.getBean("antsClustering");
		kmeansClustering = (KMeansClustering)factory.getBean("kmeansClustering");
		
		// Initializing 12 points randomly
		List<Object> points = new ArrayList<Object>();
		for (int p = 0; p < 12; p++) { 
		  points.add(new Long(p+1));
		} 
		
		// Randomly put the points
		antsClustering.initializeRandom(points, 2);
		
		// Load data from the database
		//antsClustering.initializeLoadData(points);
	}
	
	public void antCluster() {
		antsClustering.getListeners().add((AntsClusteringAlgorithmListener)this);
		
		// Running the antsClustering algorithm
		antsClustering.cluster();
	}
	
	public void antAdded(Ant ant) {
		log.info("Ant Added");
	}
	
	public void clusteringFinished(Plan plan) {
		log.info("Ants clustering finished");
		
		// Running the K-means algorithm
		List<Cluster> clusters = kmeansClustering.cluster(plan.getPoints());
		for (Cluster cluster : clusters) {
			log.info(cluster);
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		ClusterantSample sample = new ClusterantSample();
		
		//Thread.sleep(15000);
		sample.antCluster();
	}
	
}
